import os
import sys
import tkinter
from tkinter import filedialog
from tkinter.filedialog import askdirectory
from tkinter import *
from tkinter.ttk import *
from os import listdir
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import json
from matplotlib.axes import Axes
from matplotlib.figure import Figure
import gc
import matplotlib as mpl
import pandas as pd
from ttkbootstrap import Style
from tkinter import ttk
import FACT_LogConv
from datetime import datetime



class TTBreakdown():
    def __init__(self):
        self.forbiddenWorld = ["Total", "GraphIndex"]
        self.showInterface()


    def get_resource_path(self, relative_path):
        if hasattr(sys, '_MEIPASS'):
            return os.path.join(sys._MEIPASS, relative_path)
        return os.path.join(os.path.abspath("."), relative_path)


    def sortData(self):
        print("Sort: ", self.sortType.get())
        tempSave = {}
        for i in range(0, len(self.testName)-1):
            tempSave[self.testName[i]] = self.testTime[i]

        if self.sortType.get() == 0:
            return
        elif self.sortType.get() == 1:
            afterSort = dict(sorted(tempSave.items(), key = lambda x: x[0], reverse = True))
        elif self.sortType.get() == 2:
            afterSort = dict(sorted(tempSave.items(), key = lambda x: x[0], reverse = False))
        elif self.sortType.get() == 3:
            afterSort = dict(sorted(tempSave.items(), key = lambda x: x[1], reverse = True))
        elif self.sortType.get() == 4:
            afterSort = dict(sorted(tempSave.items(), key = lambda x: x[1], reverse = False))

        self.testName = []
        self.testTime = []
        for key in afterSort:
            self.testName.append(key)
            self.testTime.append(afterSort[key])


    def get_path(self):
        # global listbox
        path = filedialog.askdirectory(title='Please choose CSV log file')
        self.entry_text.set(path)
        fileName_col = listdir(path)
        tuple_fileName = tuple(fileName_col)
        var_fileName = tkinter.StringVar()
        var_fileName.set(tuple_fileName)
        self.listbox = tkinter.Listbox(self.root, width=30, height=100, listvariable=var_fileName)

        self.listbox.place(x=0, y=50)
        self.listbox.bind("<Button-1>", self.get_oneOfFilename)


    def get_oneOfFilename(self, event):
        listbox_curselection = self.listbox.curselection()
        print("listbox_curselection: ", listbox_curselection)
        try:
            filename = self.listbox.get(listbox_curselection[0])
            self.full_filename = self.entry_text.get() + '/' + filename
            print("full_filename: ", self.full_filename)
            self.createPlot(self.full_filename)
        except:
            print("please re-click")


    def createPlot(self, filename):
        # global figure, canvas_tk_agg, num, subplot, canvas, widget
        self.num = 0
        print("File Name: ",filename)

        file = filename
        df = pd.read_csv(file)
        labels = list(df.columns.values)
        if labels[0].find("TestName") >= 0:
            testNameLabel = labels[0]
        else:
            for e in labels:
                if e.find("TestName") >= 0 or e.find("ActionName") >= 0:
                    testNameLabel = e
                    break
        for e in labels:
        	if e.find("Duration") >= 0 or e.find("TestTime") >= 0:
        		testTimelabel = e
        		break
        print("testNameLabel: ", testNameLabel)
        print("testTimelabel: ", testTimelabel)

        self.testName = []
        self.testTime = []

        limit = self.inputLimit.get()
        if limit == "" or limit == None:
            limit = 0
        else:
            limit = float(limit)

        for index, row in df.iterrows():
            if float(row[testTimelabel]) >= limit:
                if row[testNameLabel] in self.testName:
                    self.testName.append(row[testNameLabel]+"_"+str(self.num))
                    self.num += 1
                else:
                	self.testName.append(row[testNameLabel])

                self.testTime.append(float(row[testTimelabel]))

        self.testName = self.testName[::-1]
        self.testTime = self.testTime[::-1]
        # if testName[len(testName)-1].find("Total") >= 0:
        #     testName.pop()
        #     testTime.pop()

        for i in range(0, len(self.testName)-1):
            for key in self.forbiddenWorld:
                try:
                    if self.testName[i].find(key) >= 0:
                        self.testName.pop(i)
                        self.testTime.pop(i)
                except:
                    break

        totalTestTime = 0
        # for e in testTime:
        #     totalTestTime = totalTestTime + e
        for index, row in df.iterrows():
            if not (row[testNameLabel].find("Total") >= 0 or row[testNameLabel].find("GraphIndex") >= 0):
                if float(row[testTimelabel]) > 0:
                    totalTestTime = totalTestTime + float(row[testTimelabel])
        self.totalTT.set(str(round(totalTestTime,3)))

        # record = {}
        # for i in range(0, len(testName)):
        #     if testTime[i] >= 1:
        #         record[testName[i]] = testTime[i]
        self.sortData()

        # plt.figure()
        self.subplot.clear()
        barhPlot = self.subplot.barh(self.testName, self.testTime, color = [(0.5,0,0), (0,0.5,0), (0,0,0.5)])
        self.subplot.bar_label(barhPlot, label_type = 'edge')

        self.saveBarPlot['state'] = 'active'

        # pieP = plt.subplot(2, 1, 2)
        # pieP.pie(testTime, labels = testName)

        # print(self.widget)
        # print(self.canvas_tk_agg)
        self.canvas_tk_agg.draw()

        self.widget.pack()


    def saveBarh(self):
        barhPlot = plt.barh(self.testName, self.testTime, color = [(0.5,0,0), (0,0.5,0), (0,0,0.5)])
        plt.bar_label(barhPlot, label_type = 'edge')
        plt.title("TT Breakdown")
        plt.show()
        plt.close()


    def saveBarh_backup(self):
        self.num = 0
        file = self.full_filename
        print("full_filename: ", file)
        df = pd.read_csv(file)
        labels = list(df.columns.values)
        if labels[0].find("TestName") >= 0:
            testNameLabel = labels[0]
        else:
            for e in labels:
                if e.find("TestName") >= 0 or e.find("ActionName") >= 0:
                    testNameLabel = e
                    break
        for e in labels:
            if e.find("Duration") >= 0 or e.find("TestTime") >= 0:
                testTimelabel = e
                break
        print("testNameLabel: ", testNameLabel)
        print("testTimelabel: ", testTimelabel)

        testName = []
        testTime = []

        limit = self.inputLimit.get()
        if limit == "" or limit == None:
            limit = 0
        else:
            limit = float(limit)

        for index, row in df.iterrows():
            if float(row[testTimelabel]) >= limit:
                if row[testNameLabel] in testName:
                    testName.append(row[testNameLabel]+"_"+str(self.num))
                    self.num += 1
                else:
                    testName.append(row[testNameLabel])
                testTime.append(float(row[testTimelabel]))

        testName = testName[::-1]
        testTime = testTime[::-1]
        # if testName[len(testName)-1].find("Total") >= 0:
        #     testName.pop()
        #     testTime.pop()
        for i in range(0, len(testName)-1):
            for key in self.forbiddenWorld:
                try:
                    if testName[i].find(key) >= 0:
                        testName.pop(i)
                        testTime.pop(i)
                except:
                    break

        barhPlot = plt.barh(testName, testTime, color = [(0.5,0,0), (0,0.5,0), (0,0,0.5)])
        plt.bar_label(barhPlot, label_type = 'edge')
        plt.title("TT Breakdown")
        plt.show()
        plt.close()


    def open_FACT_Log(self):
        path = filedialog.askdirectory(title='Please choose CSV log file')
        self.entry_text.set(path)
        fileName_col = listdir(path)
        tuple_fileName = tuple(fileName_col)
        var_fileName = tkinter.StringVar()
        var_fileName.set(tuple_fileName)
        self.listbox = tkinter.Listbox(self.root, width=30, height=100, listvariable=var_fileName)

        self.listbox.place(x=0, y=50)
        self.listbox.bind("<Button-1>", self.get_FACTLogName)


    def get_FACTLogName(self, event):
        listbox_curselection = self.listbox.curselection()
        print("listbox_curselection: ", listbox_curselection)
        try:
            filename = self.listbox.get(listbox_curselection[0])
            self.full_filename = self.entry_text.get() + '/' + filename
            print("full_filename: ", self.full_filename)
            logs = FACT_LogConv.readFACTLog(self.full_filename)
            TTBreakdown = FACT_LogConv.checkTestTime(logs)
            csvname = self.full_filename + "-" + datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ".csv"
            if not os.path.exists(csvname):
                resultName = FACT_LogConv.createCSV(TTBreakdown, csvname)
            self.full_filename = csvname
            print("FACT log path: ", self.full_filename)
            self.createPlot(self.full_filename)
        except:
            print("please re-click")


    def showInputInfo(self):
        infoWindow = Toplevel(self.root)
        infoWindow.geometry("600x400")
        infoWindow.title("导入文件说明")

        helpTitle = Label(infoWindow, text="导入文件说明", font=("Tahoma", 20, "bold"))
        helpLabel1 = Label(infoWindow, text="1. QT CSV File \n    -- For Atlas2 QT stations, please choose a folder including target CSV file", font=("Helvetica", 15))
        helpLabel2 = Label(infoWindow, text="2. FACT Log File \n    -- For R04 FACT stations, please choose a folder including FACT log file", font=("Helvetica", 15))

        helpTitle.pack(side=TOP, pady = 30)
        helpLabel1.pack(side=TOP, pady = 5)
        helpLabel2.pack(side=TOP, pady = 5)



    def about(self):
        aboutWindow = Toplevel(self.root)
        aboutWindow.geometry("450x150")
        aboutWindow.title("About")

        GTKLabel = Label(aboutWindow, text="Goertek", font=("Tahoma", 50, "bold"))
        GTKsubLabel = Label(aboutWindow, text="We make it together", font=("Tahoma", 15))
        blankLabel = Label(aboutWindow, text="", font=("Tahoma", 20))
        aboutInfo = Label(aboutWindow, text= "Copyright ©️ GTK-U01 BG-研发资源平台-测试研发中心")

        GTKLabel.pack()
        GTKsubLabel.pack()
        blankLabel.pack()
        aboutInfo.pack()


    def showInterface(self):
        style = Style(theme = "superhero")
        self.root = style.master
        # self.root = tkinter.Tk()
        # self.root.config(background="gray")

        self.root.title("TT Breakdown Analyzer")
        self.root.geometry("1500x960")

        self.label = Label(self.root, text='Choose Catalog:', width = 13, font=("Tahoma", 18, "bold"))
        # self.label.place(x=50, y=10)

        self.entry_text = StringVar()
        self.entry = Entry(self.root, textvariable=self.entry_text, width=20, state='readonly')
        # self.entry.place(x=200, y=10)

        self.tkinter_button = Menubutton(self.root, text="Choose Catalog", width = 15)
        # self.tkinter_button.place(x=450, y=10)

        self.saveBarPlot = Button(self.root, text="Save Barh Plot", command=self.saveBarh, width=15)

        self.saveBarPlot['state'] = 'disabled'

        self.TTLabel = Label(self.root, text = '    Total Test Time:', width = 15, font=("Phosphate", 22))

        self.totalTT = StringVar()
        self.TTOutput = Label(self.root, textvariable=self.totalTT, width = 15, font=("Tahoma", 22, "bold", "underline"))

        self.plotLimit = Label(self.root, text='Set Simplify Limit:', width = 15, font=("Tahoma", 17, "bold"))
        self.limit = StringVar()
        self.inputLimit = Entry(self.root, textvariable=self.limit, width=20)

        self.listbox = None

        self.figure = Figure(figsize=(16.4, 10.5), dpi=70)
        self.subplot = self.figure.add_subplot(1, 1, 1)
        # subplot.set(xlim=[0, 10],title="TT Distribution Plot")
        # subplot.xaxis.set_ticks(np.arange(0, 26, 1))

        self.canvas = Canvas(self.root)
        self.canvas_tk_agg = FigureCanvasTkAgg(self.figure, master = self.canvas)
        self.canvas_tk_agg.draw()
        self.widget = self.canvas_tk_agg.get_tk_widget()
        self.widget.pack()
        self.canvas.place(x = 280, y = 50)

        # self.label.grid(row=1, column=1, padx=10, pady=10)
        self.tkinter_button.grid(row = 1, column = 1, padx = 10, pady = 10)
        self.entry.grid(row = 1, column = 2, padx = 10, pady = 10)
        self.plotLimit.grid(row = 1, column = 3, padx = 10, pady = 10)
        self.inputLimit.grid(row = 1, column = 4, padx = 10, pady = 10)
        self.saveBarPlot.grid(row = 1, column = 5, padx = 10, pady = 10)
        self.TTLabel.grid(row = 1, column = 6, padx = 10, pady = 10)
        self.TTOutput.grid(row = 1, column = 7, padx = 10, pady = 10)

        self.menubar = Menu(self.root)
        self.filemenu = Menu(self.menubar)
        self.setmenu = Menu(self.menubar)
        self.aboutmenu = Menu(self.menubar)

        self.filemenu.add_command(label = 'QT CSV File',command = self.get_path)
        self.filemenu.add_command(label = 'FACT Log File',command = self.open_FACT_Log)
        self.menubar.add_cascade(label = '导入测试Log', menu = self.filemenu)
        self.sortType = IntVar()
        self.sortType.set(0)
        self.setmenu.add_radiobutton(label = '默认排序', variable = self.sortType, value = 0)
        self.setmenu.add_radiobutton(label = '测项名升序', variable = self.sortType, value = 1)
        self.setmenu.add_radiobutton(label = '测项名降序', variable = self.sortType, value = 2)
        self.setmenu.add_radiobutton(label = '测试时间升序', variable = self.sortType, value = 3)
        self.setmenu.add_radiobutton(label = '测试时间降序', variable = self.sortType, value = 4)
        self.menubar.add_cascade(label = '设置', menu = self.setmenu)
        self.aboutmenu.add_command(label = '说明', command = self.showInputInfo)
        self.aboutmenu.add_command(label = '关于', command = self.about)
        self.menubar.add_cascade(label = '帮助', menu=self.aboutmenu)
        self.root.config(menu = self.menubar)

        self.filemenuBtn = Menu(self.tkinter_button, tearoff=False)
        self.filemenuBtn.add_command(label = 'QT CSV File',command = self.get_path)
        self.filemenuBtn.add_command(label = 'FACT Log File',command = self.open_FACT_Log)
        self.tkinter_button.config(menu = self.filemenuBtn)

        self.root.mainloop()


if __name__ == '__main__':
    myTTBreakdown = TTBreakdown()



